package com.ghy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ghy.constant.ML;
import com.ghy.dto.EpisodeInsertDTO;
import com.ghy.dto.EpisodePageDTO;
import com.ghy.dto.EpisodeUpdateDTO;
import com.ghy.entity.Category;
import com.ghy.entity.Course;
import com.ghy.entity.Season;
import com.ghy.excel.EpisodeExcelDTO;
import com.ghy.exception.ServiceException;
import com.ghy.mapper.CommentMapper;
import com.ghy.mapper.ReportMapper;
import com.ghy.util.MinioUtil;
import com.ghy.vo.EpisodeSimpleListVO;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.ghy.entity.Episode;
import com.ghy.mapper.EpisodeMapper;
import com.ghy.service.EpisodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static com.ghy.entity.table.CommentTableDef.COMMENT;
import static com.ghy.entity.table.EpisodeTableDef.EPISODE;
import static com.ghy.entity.table.ReportTableDef.REPORT;

/**
 * 集次表 服务层实现。
 *
 * @author ghy
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "episode")
public class EpisodeServiceImpl extends ServiceImpl<EpisodeMapper, Episode>  implements EpisodeService{

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private ReportMapper reportMapper;

    @CacheEvict(allEntries = true)
    @Override
    public boolean insert(EpisodeInsertDTO dto) {
        //标题查重
        if (QueryChain.of(mapper)
                . where(EPISODE.TITLE.eq(dto.getTitle()))
                .exists()){
            throw new ServiceException("类别标题已存在");
        }

        //组装entity实体类
        Episode episode = BeanUtil.copyProperties(dto, Episode.class);
        episode.setVideo(ML.Episode.DEFAULT_VIDEO) ;
        episode.setCover(ML.Episode.DEFAULT_VIDEO_COVER);
        episode.setCreated(LocalDateTime.now());
        episode.setUpdated(LocalDateTime.now());

        return mapper.insert(episode) > 0;
    }

    @Cacheable(key = "#p0",
            condition = "#p0 != null ",
            unless = " #result == null")
    @Override
    public Episode select(Long id) {
        RelationManager.addQueryRelations("season");
        return mapper.selectOneWithRelationsById(id);
    }


    @Cacheable(key = "#root.methodName",
            unless ="#result == null")
    @Override
    public List<EpisodeSimpleListVO> simpleList(){
        //RelationManager.addQueryRelations("category", "seasons","episodes");

        return QueryChain.of(mapper)
                . orderBy(EPISODE.IDX.asc(), EPISODE.ID.desc())
                .withRelations()
                .listAs(EpisodeSimpleListVO.class);
    }

    @Cacheable(key = "#root.methodName + ':' + #p0.toString()", condition = "#p0 != null", unless = "#result == null")
    @Override
    public Page<Episode> page(EpisodePageDTO dto) {
        RelationManager.addQueryRelations("season");
        QueryChain<Episode> queryChain = QueryChain.of(mapper)
                .orderBy(EPISODE.IDX.asc(), EPISODE.ID.desc());

        //title 条件
        String title = dto.getTitle();
        if(ObjectUtil.isNotNull(title)){
            queryChain.where(EPISODE. TITLE.like(title));
        }

        //seasonId 条件
        Long seasonId = dto.getFkSeasonId();
        if (ObjectUtil.isNotNull(seasonId)) {
            queryChain.where(EPISODE.FK_SEASON_ID.eq( seasonId));
        }

        return queryChain.withRelations()
                .page(new Page<>(dto.getPageNum(), dto.getPageSize()));
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean update(EpisodeUpdateDTO dto) {
        //标题查重
        if (QueryChain.of(mapper)
                . where(EPISODE.TITLE.eq(dto.getTitle()))
                .and(EPISODE.ID.ne(dto.getId()))
                .exists()){
            throw new ServiceException("集次标题已存在");
        }

        //组装entity实体类
        Episode episode = BeanUtil.copyProperties(dto, Episode.class);
        episode.setUpdated(LocalDateTime.now());

        return UpdateChain.of(episode)
                . where(EPISODE.ID.eq(episode.getId()))
                . update();
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {

        // 查询该集次关联的全部评论ID
        // select id from comment where fk_episode_id = ?
        List<Long> commentIds = QueryChain.of(commentMapper)
                .select(COMMENT.ID)
                .where(COMMENT.FK_EPISODE_ID.eq(id))
                .listAs(Long.class);

        // 查询该集次关联的全部评论的子评论ID
        // select id from comment where pid in (commentIds)
        List<Long> subCommentIds = QueryChain.of(commentMapper)
                .select(COMMENT.ID)
                .where(COMMENT.PID.in(commentIds))
                .listAs(Long.class);

        // 组合全部待删除的评论ID
        commentIds.addAll(subCommentIds);

        // 删除该集次的全部评论
        // delete from comment where id in (commentIds)
        UpdateChain.of(commentMapper)
                .where(COMMENT.ID.in(commentIds))
                .remove();

        // 删除该集次的全部举报
        // delete from report where fk_episode_id =?
        UpdateChain.of(reportMapper)
                .where(REPORT.FK_EPISODE_ID.eq(id))
                .remove();

        // 删除集次
        // delete from episode where id =?
        return mapper.deleteById(id) > 0;
    }


    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteBatch(List<Long> ids) {
        // 查询该集次关联的全部评论ID
        // select id from comment where fk_episode_id = ?
        List<Long> commentIds = QueryChain.of(commentMapper)
                .select(COMMENT.ID)
                .where(COMMENT.FK_EPISODE_ID.eq(ids))
                .listAs(Long.class);

        // 查询该集次关联的全部评论的子评论ID
        // select id from comment where pid in (commentIds)
        List<Long> subCommentIds = QueryChain.of(commentMapper)
                .select(COMMENT.ID)
                .where(COMMENT.PID.in(commentIds))
                .listAs(Long.class);

        // 组合全部待删除的评论ID
        commentIds.addAll(subCommentIds);

        // 删除该集次的全部评论
        // delete from comment where id in (commentIds)
        UpdateChain.of(commentMapper)
                .where(COMMENT.ID.in(commentIds))
                .remove();

        // 删除该集次的全部举报
        // delete from report where fk_episode_id =?
        UpdateChain.of(reportMapper)
                .where(REPORT.FK_EPISODE_ID.eq(ids))
                .remove();

        // 删除集次
        // delete from episode where id =?
        return mapper.deleteBatchByIds(ids) > 0;
    }

    @CacheEvict(allEntries = true)
    @Override
    public String uploadVideoCover(MultipartFile videoCoverFile, Long id) {
        //按主键查询用户记录
        Episode episode = mapper.selectOneById(id);
        if (ObjectUtil.isNull(episode)) {
            throw new ServiceException("集次不存在");
        }

        //备份旧头像
        String oldCover = episode.getCover();
        //重新生成文件名
        String filename = MinioUtil.randomFilename(videoCoverFile);

        //根据用户主键修改用户头像
        episode.setCover(filename);
        if (mapper.update(episode)<= 0) {
            throw new ServiceException("集次封面更新失败：DB操作异常");
        }
        try {
            //从MinI0中删除旧头像：默认头像不删除
            if (!ML.Episode.DEFAULT_VIDEO_COVER.contains(oldCover)) {
                MinioUtil.delete(oldCover, ML.MinIO.EPISODE_VIDEO_COVER_DIR, ML.MinIO.BUCKET_NAME);
            }
            //向MinIO中上传新头像
            MinioUtil.upload(videoCoverFile, filename, ML.MinIO.EPISODE_VIDEO_COVER_DIR, ML.MinIO.BUCKET_NAME);

        }catch (Exception e){
            throw new ServiceException("集次封面更新失败：MinIo操作异常");
        }
        //返回文件名
        return filename;
    }

    @Override
    public String uploadVideo(MultipartFile videoFile, Long id) {
        //按主键查询用户记录
        Episode episode = mapper.selectOneById(id);
        if (ObjectUtil.isNull(episode)) {
            throw new ServiceException("集次不存在");
        }

        //备份旧头像
        String oldVideo = episode.getVideo();
        //重新生成文件名
        String filename = MinioUtil.randomFilename(videoFile);

        //根据用户主键修改用户头像
        episode.setVideo(filename);
        if (mapper.update(episode)<= 0) {
            throw new ServiceException("集次视频更新失败：DB操作异常");
        }
        try {
            //从MinI0中删除旧头像：默认头像不删除
            if (!ML.Episode.DEFAULT_VIDEO.contains(oldVideo)) {
                MinioUtil.delete(oldVideo, ML.MinIO.EPISODE_VIDEO_DIR, ML.MinIO.BUCKET_NAME);
            }
            //向MinIO中上传新头像
            MinioUtil.upload(videoFile, filename, ML.MinIO.EPISODE_VIDEO_DIR, ML.MinIO.BUCKET_NAME);

        }catch (Exception e){
            throw new ServiceException("集次视频更新失败：MinIo操作异常");
        }
        //返回文件名
        return filename;
    }

    @Override
    public List<EpisodeExcelDTO> excel(){

        //加1层递归深度：episode -〉season ->course -〉category
        RelationManager.setMaxDepth(4);

        //查询全部集次记录
        List<Episode> episodes = mapper.selectAllWithRelations();

        // List<Episode> -> List<EpisodeExcelDTO>
        List<EpisodeExcelDTO> result = new ArrayList<>();
        episodes.forEach(episode -> {
            //赋值 Episode 相关信息
            EpisodeExcelDTO episodeExcelDTO = BeanUtil.copyProperties(episode, EpisodeExcelDTO.class);

            //赋值 Season 相关信息
            Season season = episode.getSeason();
            episodeExcelDTO.setSeasonTitle(season.getTitle());
            episodeExcelDTO.setSeasonInfo(season.getInfo());

            //赋值Course 相关信息
            Course course = season.getCourse();
            episodeExcelDTO.setCourseTitle(course.getTitle());
            episodeExcelDTO.setCourseInfo(course.getInfo());
            episodeExcelDTO.setPrice(course.getPrice());
            episodeExcelDTO.setAuthor(course.getAuthor());

            //赋值Category 相关信息
            Category category = course.getCategory();
            episodeExcelDTO.setCategoryTitle(category.getTitle());
            result.add(episodeExcelDTO);
        });
        return result;
    }

}
